﻿using ShiQuan.LogHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ShiQuan.RemoteHelper
{
    /// <summary>
    /// 远程主机配置信息
    /// </summary>
    public class RemoteMachineHelper
    {
        /// <summary>
        /// 配置文件目录
        /// </summary>
        public static string FilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RemoteMachine");

        private static List<RemoteMachine> _remotes = null;
        /// <summary>
        /// 读取配置信息
        /// </summary>
        /// <returns></returns>
        public static List<RemoteMachine> Read()
        {
            if (_remotes != null)
                return _remotes;

            try
            {
                if (System.IO.Directory.Exists(RemoteMachineHelper.FilePath) == false)
                    System.IO.Directory.CreateDirectory(RemoteMachineHelper.FilePath);

                _remotes = new List<RemoteMachine>();

                RemoteMachine remote = null;
                string[] files = System.IO.Directory.GetFiles(RemoteMachineHelper.FilePath, "*.xml");
                for (int i = 0; i < files.Length; i++)
                {
                    remote = RemoteMachineHelper.Read(files[i]);
                    if (remote == null)
                        continue;

                    RemoteMachineHelper._remotes.Add(remote);
                }
                return RemoteMachineHelper._remotes;
            }
            catch (Exception ex)
            {
                Logger.Error("读取配置信息异常", ex);
                return null;
            }
        }
        /// <summary>
        /// 读取配置信息
        /// </summary>
        /// <returns></returns>
        public static RemoteMachine Read(string fileName)
        {
            if (System.IO.File.Exists(fileName) == false)
                return null;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(fileName);

                XmlElement root = doc.DocumentElement;
                if (root.Name != "RemoteMachine")
                    return null;

                RemoteMachine remote = new RemoteMachine();
                foreach (XmlNode item in root.ChildNodes)
                {
                    remote.Set(item.Name, item.InnerText);
                }
                if (string.IsNullOrEmpty(remote.Id))
                    return null;

                return remote;
            }
            catch (Exception ex)
            {
                Logger.Error("读取配置信息异常", ex);
                return null;
            }
        }
        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <returns></returns>
        public static RemoteMachine Get(string keyValue)
        {
            List<RemoteMachine> dic = RemoteMachineHelper.Read();
            for (int i = 0; i < dic.Count; i++)
            {
                if (dic[i].Id == keyValue)
                    return dic[i];
            }
            return null;
        }
        /// <summary>
        /// 保存配置信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="remote"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static bool Save(string keyValue, RemoteMachine remote, out string errorMsg)
        {
            errorMsg = string.Empty;
            try
            {
                if (System.IO.Directory.Exists(RemoteMachineHelper.FilePath) == false)
                    System.IO.Directory.CreateDirectory(RemoteMachineHelper.FilePath);

                if (string.IsNullOrEmpty(keyValue))
                    remote.Id = Guid.NewGuid().ToString();
                else
                    remote.Id = keyValue;

                //创建远程桌面
                var rdesktopInfo = new RdpDesktop.RDesktopInfo();
                rdesktopInfo.FullAddress = remote.Server;
                rdesktopInfo.UserName = remote.Account;
                rdesktopInfo.Password = remote.Password;
                rdesktopInfo.DesktopWidth = remote.DesktopWidth;
                rdesktopInfo.DesktopHeight = remote.DesktopHeight;

                var rdesktop = RdpDesktop.RDesktopHelper.GetRdesktop(rdesktopInfo);
                var rdesktopFile = System.IO.Path.Combine(RemoteMachineHelper.FilePath, remote.Id + ".rdp");
                System.IO.File.WriteAllText(rdesktopFile, rdesktop);

                remote.RdesktopFile = rdesktopFile;
                //保存配置信息
                XmlDocument doc = new XmlDocument();
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
                XmlElement root = doc.CreateElement("RemoteMachine");
                foreach (var fieldValue in remote.GetFieldValue())
                {
                    XmlElement node = doc.CreateElement(fieldValue.Key);
                    node.InnerText = fieldValue.Value;
                    root.AppendChild(node);
                }
                doc.AppendChild(root);

                var fileName = System.IO.Path.Combine(RemoteMachineHelper.FilePath, remote.Id + ".xml");
                doc.Save(fileName);

                //更新缓存
                if (string.IsNullOrEmpty(keyValue))
                    RemoteMachineHelper._remotes.Add(remote);
                else
                {
                    for (int i = 0; i < RemoteMachineHelper._remotes.Count; i++)
                    {
                        RemoteMachine item = RemoteMachineHelper._remotes[i];
                        if (item.Id == keyValue)
                            item = remote;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error("保存配置信息异常", ex);
                errorMsg = "保存配置信息异常";
                return false;
            }
        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <returns></returns>
        public static bool Remove(string keyValue)
        {
            //List<RemoteMachine> dic = RemoteHelper.Read();
            //for (int i = dic.Count -1; i >= 0; i--)
            //{
            //    if (dic[i].Id == keyValue)
            //    {
            //        dic.RemoveAt(i);
            //    }
            //}

            var fileName = System.IO.Path.Combine(RemoteMachineHelper.FilePath, keyValue + ".xml");
            if (System.IO.File.Exists(fileName))
                System.IO.File.Delete(fileName);
            //RemoteHelper._remotes = null;
            return true;
        }
    }
}
